﻿using Newtonsoft.Json;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using ThirdParty.Application.Config;
using ThirdParty.Application.ThirdParty.Interfaces;
using Microsoft.Extensions.DependencyInjection;
using ThirdParty.Application.Model.ViewModel.Response.WxProgram;
using LDM.Business.Repository.Repository.Interfaces;
using Logs;

namespace ThirdParty.Application.Tencent
{
    public class WxProgram : IWxProgramService
    {
        /// <summary>
        /// 系统配置参数
        /// </summary>
        private readonly ISystemConfigRepository _systemConfigRepository;

        public WxProgram(ISystemConfigRepository systemConfigRepository)
        {
            _systemConfigRepository = systemConfigRepository;
        }

        /// <summary>
        /// 微信小程序登录  
        /// 获取OpenID、session_key
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public WxLoginResponse Wxlogin(string code)
        {
            var sysconfig = _systemConfigRepository.GetSystemConfig();
            try
            {
                //获取AccessToken
                string AccessTokenUrl = $"{WxConstStr.code2Session}?" +
                    $"appid={sysconfig.WxProAppID}&" +
                    $"secret={sysconfig.WxProAppSecret}&" +
                    $"js_code={code}&" +
                    $"grant_type=authorization_code";
                string loginResult = RequestUrl(AccessTokenUrl, "GET");
                return JsonConvert.DeserializeObject<WxLoginResponse>(loginResult);
            }
            catch (Exception ex)
            {
                Log.GetLog(this).Error(ex.Message);
                return new WxLoginResponse { errcode = 9999, errmsg = ex.Message };
            }
        }

        /// <summary>
        /// 获取接口调用凭据
        /// 获取accessToken
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public string GetAccessToken()
        {
            var sysconfig = _systemConfigRepository.GetSystemConfig();
            try
            {
                string AccessTokenUrl = $"{WxConstStr.getAccessToken}?" +
                    $"appid={sysconfig.WxProAppID}&" +
                    $"secret={sysconfig.WxProAppSecret}&" +
                    $"grant_type=client_credential";
                string AccessTokenResult = RequestUrl(AccessTokenUrl, "GET");
                string ErrCode = GetJsonValue(AccessTokenResult, "errcode");
                if (!string.IsNullOrWhiteSpace(ErrCode))
                {
                    Log.GetLog().Warn(AccessTokenResult);
                    return string.Empty;
                }
                string accessToken = GetJsonValue(AccessTokenResult, "access_token");
                string expiresIn = GetJsonValue(AccessTokenResult, "expires_in");
                return accessToken;
            }
            catch (Exception ex)
            {
                Log.GetLog(this).Error(ex.Message);
                return ex.Message;
            }
        }


        /// <summary>
        /// 获取接口调用凭据
        /// 根据code获得用户手机号
        /// 获取accessToken
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public string GetPhoneNumber(string code)
        {
            //var sysconfig = _systemConfigRepository.GetSystemConfig();
            try
            {
                //获取AccessToken
                var accessToken = GetAccessToken();
                if (string.IsNullOrWhiteSpace(accessToken))
                    return string.Empty;
                string AccessTokenUrl = $"{WxConstStr.getuserphonenumber}?access_token={accessToken}";
                var json = JsonConvert.SerializeObject(new { code });
                string AccessTokenResult = RequestUrl(AccessTokenUrl, "POST", json);
                string ErrCode = GetJsonValue(AccessTokenResult, "errcode");
                if (!string.IsNullOrWhiteSpace(ErrCode) || ErrCode != "0")
                    return AccessTokenResult;
                //string accessToken = GetJsonValue(AccessTokenResult, "access_token");
                //string expiresIn = GetJsonValue(AccessTokenResult, "expires_in");
                return AccessTokenResult;
            }
            catch (Exception ex)
            {
                Log.GetLog(this).Error(ex.Message);
                return ex.Message;
            }
        }

        /// <summary>
        /// 发起请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        private static string RequestUrl(string url, string method, string data = "")
        {
            // 设置参数
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = method;
            request.ContentType = "text/html";
            request.Headers.Add("charset", "utf-8");
            if (!string.IsNullOrEmpty(data))
            {
                using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream()))
                    streamWriter.Write(data);
            }
            //发送请求并获取相应回应数据
            var response = (HttpWebResponse)request.GetResponse();
            using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                string content = sr.ReadToEnd();
                return content;
            }
        }


        private static string GetJsonValue(string jsonStr, string key)
        {
            string result = string.Empty;
            if (!string.IsNullOrEmpty(jsonStr))
            {
                key = "\"" + key.Trim('"') + "\"";
                int index = jsonStr.IndexOf(key) + key.Length + 1;
                if (index > key.Length + 1)
                {
                    //先截逗号，若是最后一个，截“｝”号，取最小值
                    int end = jsonStr.IndexOf(',', index);
                    if (end == -1)
                    {
                        end = jsonStr.IndexOf('}', index);
                    }
                    result = jsonStr.Substring(index, end - index);
                    result = result.Trim(new char[] { '"', ' ', '\'' }); //过滤引号或空格
                }
            }
            return result;
        }



        /// <summary>
        /// 微信授权 解码获得用户手机号
        /// </summary>
        /// <param name="encryptedData"></param>
        /// <param name="aesIv"></param>
        /// <param name="session_key"></param>
        /// <param name="wechatId"></param>
        /// <returns></returns>
        public string GetPhoneNumber(string encryptedData, string aesIv, string session_key, string wechatId)
        {
            try
            {
                session_key = session_key.Replace("\\", "");
                byte[] encryData = Convert.FromBase64String(encryptedData);
                Aes aes = Aes.Create();
                aes.Key = Convert.FromBase64String(session_key);
                aes.IV = Convert.FromBase64String(aesIv);
                aes.Mode = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7;
                ICryptoTransform transform = aes.CreateDecryptor();
                byte[] plainText = transform.TransformFinalBlock(encryData, 0, encryData.Length);
                string result = Encoding.Default.GetString(plainText);
                dynamic model = Newtonsoft.Json.Linq.JToken.Parse(result) as dynamic;
                string phoneNumber = model.phoneNumber;
                //return model.phoneNumber;
                if (string.IsNullOrEmpty(phoneNumber))
                {
                    return "";
                }
                return phoneNumber;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

    }
}
